package com.douwong.student.services;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;

import com.douwong.student.contant.CommonConfig;
import com.douwong.student.core.ResourceLoadThread;
import com.douwong.student.db.PrepareReaourceDBService;
import com.douwong.student.interfaces.UpdatePro;
import com.douwong.student.model.PrepareResource;
import com.douwong.student.utils.JsonUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 资源下载服务
 * 
 * @author leihuajie
 * 
 */
public class ResourceLoadService extends Service implements UpdatePro {

	private ArrayList<HashMap<String, Object>> threadList;
	private ArrayList<PrepareResource> list;
	private int lastIndex=-1;
	private ExecutorService pool;
	private String TAG="ResourceLoadService";

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			Log.i(TAG, "recieve download action.....");
			if (action.equals(CommonConfig.BEGIN_LOAD_RESOURCE)) {// 開始下載
				String resource = intent.getStringExtra("resource");
				PrepareResource prepareResource = JsonUtils.deserialize(
						resource, PrepareResource.class);
				list.add(prepareResource);
				ResourceLoadThread thread = new ResourceLoadThread(
						prepareResource.getDownLoadUrl(),
						prepareResource.getFileName(), prepareResource.getId(),
						ResourceLoadService.this);
				thread.updateLoadPro(ResourceLoadService.this);
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("fileId", prepareResource.getId());
				map.put("loadThread", thread);
				map.put("id", lastIndex);
				threadList.add(map);
				pool.execute(thread);
//				if(threadList.size()<5){
//					thread.start();
//				}
				
			} else if (action.equals(CommonConfig.STOP_LOAD_RESOURCE)) {// 暫停下載
				int fileId = intent.getIntExtra("fileId", -1);
				for (int i = 0; i < threadList.size(); i++) {
					HashMap<String, Object> map = threadList.get(i);
					Log.e("fileId", fileId + "");
					if (fileId == (Integer) map.get("fileId")) {
						ResourceLoadThread thread = (ResourceLoadThread) map
								.get("loadThread");
						thread.setLoad(false);
						threadList.remove(i);
						break;
					}
				}
			} else if (action.equals(CommonConfig.CONTINUE_LOAD_RESOURCE)) {// 暫停后繼續下載
				String resource = intent.getStringExtra("resource");
				PrepareResource prepareResource = JsonUtils.deserialize(
						resource, PrepareResource.class);
				list.add(prepareResource);
				ResourceLoadThread thread = new ResourceLoadThread(
						prepareResource.getDownLoadUrl(),
						prepareResource.getFileName(), prepareResource.getId(),
						ResourceLoadService.this);
				thread.updateLoadPro(ResourceLoadService.this);
				thread.setStop(true);
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("fileId", prepareResource.getId());
				map.put("loadThread", thread);
				threadList.add(map);
				pool.execute(thread);
			} else if (action.equals(CommonConfig.CLOSE_RESOURCE_LOAD)) {// 刪除下載
				int fileId = intent.getIntExtra("fileId", -1);
				for (int i = 0; i < threadList.size(); i++) {
					HashMap<String, Object> map = threadList.get(i);
					if (fileId == (Integer) map.get("fileId")) {
						ResourceLoadThread thread = (ResourceLoadThread) map
								.get("loadThread");
						thread.setLoad(false);
						threadList.remove(i);
						break;
					}
				}
			}
		}
	};

	IntentFilter filter = new IntentFilter() {
		{
			addAction(CommonConfig.BEGIN_LOAD_RESOURCE);
			addAction(CommonConfig.STOP_LOAD_RESOURCE);
			addAction(CommonConfig.CONTINUE_LOAD_RESOURCE);
			addAction(CommonConfig.CLOSE_RESOURCE_LOAD);
		}
	};

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		threadList = new ArrayList<HashMap<String, Object>>();
		list = new ArrayList<PrepareResource>();
//		pool = Executors.newCachedThreadPool(5);
		pool=Executors.newFixedThreadPool(5); 
		registerReceiver(receiver, filter);
		Log.i(TAG, "ResourceLoadService create success");

	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i("ResourceLoadService", "ResourceLoadService launch success");
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void update(long progress, int fileId) {
		for (int i = 0; i < list.size(); i++) {
			if (fileId == list.get(i).getId()) {
				Intent updateIntent = new Intent();
				updateIntent.setAction(CommonConfig.RESOURCE_UPDATE);
				updateIntent.putExtra("pro", progress);
				updateIntent.putExtra("fileId", fileId);
				sendBroadcast(updateIntent);
				break;
			}
		}

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(receiver);
		Log.i(TAG, "ResourceLoadService stop");
	}

	@Override
	public void loadCompleted(int fileId) {
		for (int i = 0; i < list.size(); i++) {
			if (fileId == list.get(i).getId()) {
				// 下载完了
				list.get(i).setLoaded(true);
				list.get(i).setLoading(false);
				list.get(i).setPause(false);
				PrepareReaourceDBService.getInstance(this).upDate(list.get(i));
				PrepareReaourceDBService.getInstance(this).upDateLoading(list.get(i));
				Intent finishIntent = new Intent();
				finishIntent.setAction(CommonConfig.RESOURCE_LOAD_COMPLETED);
				finishIntent.putExtra("fileId", fileId);
				sendBroadcast(finishIntent);
				for(int j=0;j<threadList.size();j++){
					HashMap<String, Object> map = threadList.get(j);
					if (fileId == (Integer) map.get("fileId")) {
						threadList.remove(j);
						break;
					}
				}
				break;
			}

		}
		
//		for(int k=0;k<threadList.size();k++){
//			HashMap<String, Object> map = threadList.get(k);
//			if (fileId == (Integer) map.get("fileId")) {
//				threadList.remove(i);
//				break;
//			}
//		}
		
		
	}

}
